package com.zeropoint.demo.shiro;

import com.alibaba.fastjson.JSONObject;
import com.zeropoint.demo.jwt.JwtToken;
import com.zeropoint.demo.mapper.UserMapper;
import com.zeropoint.demo.pojo.RolePO;
import com.zeropoint.demo.pojo.UserPO;
import com.zeropoint.demo.service.UserService;
import com.zeropoint.demo.util.JwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;



    /**
     * 必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        // 执行认证
        String username = JwtUtil.getClaim(principals.toString());
        UserPO user = userMapper.getUserByName(username);
        //构建权限的类
        SimpleAuthorizationInfo sai=new SimpleAuthorizationInfo();
        Set<String> proleList=new HashSet<>();
        //有问题后续要改（查找权限的）
			if(user!=null){
				List<RolePO> lrole = userMapper.getRoleById(user.getUid());
				for (RolePO role : lrole) {
					proleList.add(role.getName());
				}
			}
        sai.setRoles(proleList);
        return sai;
    }

    /**
     * 进行token 认证
     * @param auth
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {


        String token = (String) auth.getCredentials();

        // 获得username，用于和数据库进行对比
        String username = null;
        try {
             username = JwtUtil.getClaim(token);
        }catch (Exception e){
            throw new AuthenticationException("token非法，不是规范的token，可能被篡改了，或者过期了");
        }


        if (username == null || !JwtUtil.verify(token)){
            throw new AuthenticationException("token无效");
        }

        UserPO user = userMapper.getUserByName(username);
        if (user == null) {
            throw new AuthenticationException("用户不存在!");
        }

        /*
        * 第一个参数传入用户名/对象 Securityutis.getsubject().getprincipal();
        * 第二个参数传入从数据库获得的 password
        * 第三个参数传入用于加密的盐值
        * 第四个参数传入当前 realm 名字
        * */
        // 认证成功
        return new SimpleAuthenticationInfo(token, token, "myRealm");
    }

}